import 'dart:async';
import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/singleton/constant_repository/constant_repository.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/smart_home/event/refresh_smart_home_index_event.dart';
import 'package:e_reception_flutter/ui/smart_home/event/refresh_style_image_event.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_3d_link_detail_page.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_column_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_folder_banner_image_page.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_folder_image_detail_page.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_store_detail_all_list_view_model.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_store_detail_common_view_model.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_store_detail_type_list_view_model.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_image_detail_page.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_store_detail_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_store_detail_view_model.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_date_time_utils.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/utils/vg_string_utils.dart';
import 'package:e_reception_flutter/vg_widgets/staggered/widgets/staggered_grid_view.dart';
import 'package:e_reception_flutter/vg_widgets/staggered/widgets/staggered_tile.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/mixin/vg_place_holder_status_mixin.dart';
import 'package:e_reception_flutter/vg_widgets/vg_pull_to_refresh_widget/vg_pull_to_refresh_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_pull_to_refresh_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
/// 品牌或门店详情下方瀑布流页面
class SmartHomeStoreDetailListWidgetNew extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "SmartHomeStoreDetailListWidgetNew";

  final String shid;
  final String samplePush;
  //栏目分类
  final String scid;
  final String title;
  final String column;
  final List<ColumnListBean> columnList;
  //风格
  final String styles;
  //类型/空间id
  final String stids;
  //类型/空间名
  final String stnames;


  const SmartHomeStoreDetailListWidgetNew({Key key, this.shid, this.samplePush,
    this.scid, this.column, this.title, this.columnList,
    this.styles, this.stids, this.stnames
  }) : super(key:key);

  @override
  _SmartHomeStoreDetailListWidgetNewState createState() => _SmartHomeStoreDetailListWidgetNewState();

}


class _SmartHomeStoreDetailListWidgetNewState extends BasePagerState<SmartHomeStoreDetailListItemBean, SmartHomeStoreDetailListWidgetNew>
    with AutomaticKeepAliveClientMixin, VgPlaceHolderStatusMixin {

  BasePagerViewModel _viewModel;
  SmartHomeStoreDetailCommonViewModel _commonViewModel;
  StreamSubscription _updateStreamSubscription;
  String _styles;
  String _lastStyles;
  String _stids;
  String _stnames;
  @override
  void initState() {
    super.initState();
    print("scid:" + widget?.scid);
    _styles = widget?.styles;
    _lastStyles = _styles;
    _stids = widget?.stids;
    _stnames = widget?.stnames;
    _commonViewModel = new SmartHomeStoreDetailCommonViewModel(this);
    _viewModel = new SmartHomeStoreDetailTypeListViewModel(this,
      shid: widget?.shid,
      scid: widget?.scid,
      samplePush: widget?.samplePush,
      scname: widget?.column,
      styles: _styles,
      stids: _stids,
      stnames: _stnames);

    //全屋
    if("-1" == widget?.scid){
      _viewModel = new SmartHomeStoreDetailAllListViewModel(this,
        shid: widget?.shid,
        scid: widget?.scid,
        samplePush: widget?.samplePush,
      );
    }
    _viewModel.refresh();
    _updateStreamSubscription =
        VgEventBus.global.streamController.stream.listen((event) {
          if(event is RefreshSmartHomeIndexEvent){
            _viewModel.refresh();
            return;
          }
          if(event is RefreshStyleImageEvent){
            _styles = event?.style??"";
            if("-1" == widget?.scid){
              //如果是全屋
              if(_viewModel is SmartHomeStoreDetailAllListViewModel){
                if(StringUtils.isNotEmpty(_styles)){
                  //风格不为空,变换使用得ViewModel
                  _viewModel = new SmartHomeStoreDetailTypeListViewModel(this,
                      shid: widget?.shid,
                      scid: "",
                      samplePush: widget?.samplePush,
                      scname: widget?.column,
                      styles: _styles,
                      stids: _stids,
                      stnames: _stnames);
                  _viewModel.refresh();
                }else{
                  //风格为空，doNothing
                }
              }else{
                //当前是other类型得ViewModel
                if(StringUtils.isNotEmpty(_styles)){
                  //风格不为空,并且没变化，直接刷新数据即可
                  if(_styles != _lastStyles){
                    _viewModel = new SmartHomeStoreDetailTypeListViewModel(this,
                        shid: widget?.shid,
                        scid: "",
                        samplePush: widget?.samplePush,
                        scname: widget?.column,
                        styles: _styles,
                        stids: _stids,
                        stnames: _stnames);
                  }
                  _viewModel.refresh();
                }else{
                  //风格为空，变换为全屋的viewmodel
                  _viewModel = new SmartHomeStoreDetailAllListViewModel(this,
                    shid: widget?.shid,
                    scid: widget?.scid,
                    samplePush: widget?.samplePush,
                  );
                  _viewModel.refresh();
                }
              }

            }else{
              //不是全屋，值更新，直接刷新数据即可
              if(_styles != _lastStyles){
                _viewModel = new SmartHomeStoreDetailTypeListViewModel(this,
                    shid: widget?.shid,
                    scid: widget?.scid,
                    samplePush: widget?.samplePush,
                    scname: widget?.column,
                    styles: _styles,
                    stids: _stids,
                    stnames: _stnames);
              }
              _viewModel.refresh();
            }
            _lastStyles = _styles;
            return;
          }
        });
  }

  @override
  void dispose() {
    _updateStreamSubscription?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return _toPlaceHolderWidget();
  }

  Widget _toPlaceHolderWidget(){
    return  MixinPlaceHolderStatusWidget(
        emptyOnClick: () => _viewModel?.refresh(),
        errorOnClick: () => _viewModel.refresh(),
        emptyWidget: _defaultEmptyCustomWidget(("综合" == (widget?.column??""))?"可展示品牌活动等海报内容～":"暂无内容"),
        errorWidget: _defaultEmptyCustomWidget("网络断线 重新获取"),
        // child: child,
        child: VgPullRefreshWidget.bind(
            state: this,
            refreshBgColor: Colors.white,
            viewModel: _viewModel,
            child: _toStaggeredWidget())
    );
  }

  Widget _defaultEmptyCustomWidget(String msg) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        Image.asset(
          "images/icon_smart_home_empty.png",
          width: 120,
          gaplessPlayback: true,
        ),
        SizedBox(
          height: 8,
        ),
        Text(
          msg??"暂无内容",
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(
            color: VgColors.INPUT_BG_COLOR,
            fontSize: 13,
          ),
        )
      ],
    );
  }

  ///瀑布流
  Widget _toStaggeredWidget(){
    return StaggeredGridView.countBuilder(
      padding: const EdgeInsets.symmetric(horizontal: 5.0),
      crossAxisCount: 4,
      itemCount: data?.length,
      shrinkWrap: true,
      staggeredTileBuilder: (int index){
        return new StaggeredTile.fit(2);
      },
      mainAxisSpacing: 5.0,
      crossAxisSpacing: 5.0,
      itemBuilder: (context, index){
        return _toItemWidget(index);
      },
    );

  }

  ///图片item
  Widget _toItemWidget(int index){
    if(data == null || (data?.isEmpty??true)){
      return Container();
    }
    SmartHomeStoreDetailListItemBean itemBean = data[index];
    String url = itemBean?.getCover();
    String picid = itemBean?.picid;
    bool isVideo = itemBean?.isVideo();
    bool is3DLink = itemBean?.is3DLink();
    bool showVideoOrLinkIcon = isVideo || is3DLink;
    String asset = "";
    if(showVideoOrLinkIcon){
      if(isVideo){
        asset = "images/icon_smart_home_video_play.png";
      }
      if(is3DLink){
        asset = "images/icon_smart_home_3d_link.png";
      }
    }

    String videoId = itemBean?.videoid;
    double imgWidth = (ScreenUtils.screenW(context) - 15)/2;
    double imgHeight = 0;
    int picWidth = int.parse(itemBean?.getPicSize()?.split("*")[0]);
    int picHeight = int.parse(itemBean?.getPicSize()?.split("*")[1]);

    double scale = picHeight/picWidth;
    if(scale == 1){
      imgHeight = imgWidth;
    }else{
      if(scale >= 1.1){
        imgHeight = (imgWidth*4)/3;
      }else{
        // imgHeight = (imgWidth *3)/4;
        imgHeight = imgWidth;
      }
    }
    String title = "未命名";
    Color titleColor = Color(0XFF8B93A5);
    if(StringUtils.isNotEmpty(itemBean?.title??"")){
      title = itemBean?.title;
      titleColor = ThemeRepository.getInstance().getCardBgColor_21263C();
    }else if(StringUtils.isNotEmpty(itemBean?.backup??"")){
      title = itemBean?.backup;
      titleColor = ThemeRepository.getInstance().getCardBgColor_21263C();
    }

    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        VgHudUtils.show(context);
        _commonViewModel.getFolderDetail(context, widget?.shid, itemBean?.sfid,
            itemBean?.getFlg(), itemBean?.picid??"", (folderDetailData){
              VgHudUtils.hide(context);
              print("scid:" + widget?.scid);
              if(itemBean?.type == "01"){
                //style为空，代表未筛选，进组图页面
                if(("-1" == widget?.scid)  && StringUtils.isEmpty(_styles) && (itemBean?.isMultiImage()??false)){
                  SmartHomeFolderImageDetailPage.navigatorPush(context, widget?.shid, widget?.scid, widget?.title, folderDetailData, widget?.columnList);
                }else{
                  SmartHomeFolderBannerImagePage.navigatorPush(context, widget?.scid,
                      "01", widget?.title, folderDetailData, widget?.columnList,
                      selectIndex: 0, picid: itemBean?.picid);
                }

              }else if(itemBean?.type == "03"){
                SmartHome3DLinkDetailPage.navigatorPush(context, widget?.scid, itemBean?.type, widget?.title, folderDetailData, widget?.columnList);
              }else{
                SmartHomeFolderBannerImagePage.navigatorPush(context, widget?.scid, itemBean?.type, widget?.title, folderDetailData, widget?.columnList);
              }
            });
      },
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          ClipRRect(
            borderRadius: BorderRadius.only(topLeft: Radius.circular(4), topRight: Radius.circular(4)),
            child: Stack(
              children: [
                Container(
                  width: imgWidth,
                  height: imgHeight,
                  child: VgCacheNetWorkImage(
                    url,
                    width: imgWidth,
                    height: imgHeight,
                    imageQualityType: ImageQualityType.middle,
                  ),
                ),
                Positioned(
                  left: imgWidth/2 - 20,
                  top: imgHeight/2 - 20,
                  child: Visibility(
                    visible: showVideoOrLinkIcon,
                    child: Image.asset(
                      asset,
                      width: 40,
                      height: 40,
                    ),
                  ),
                ),
                Visibility(
                  visible: itemBean?.isExample(),
                  child: Positioned(
                    top: 7,
                    left: 7,
                    child: Image.asset(
                      "images/icon_smart_home_example.png",
                      width: 29,
                      height: 16,
                    ),
                  ),
                ),
                Positioned(
                  top: 0,
                  right: 0,
                  child: Visibility(
                    visible: (isVideo?? false),
                    child: Container(
                      width: 37,
                      height: 16,
                      decoration: BoxDecoration(
                          color: Color(0XFF000000).withOpacity(0.7),
                          borderRadius: BorderRadius.only(
                              bottomLeft: Radius.circular(4),
                              topRight: Radius.circular(4))),
                      child: Center(
                        child: Text(
                          VgDateTimeUtils.getSecondsToMinuteStr(data[index].videotime) ?? "00:00",
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                              color: Colors.white,
                              fontSize: 9,
                              height: 1.2
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
                Positioned(
                  top: 6,
                  right: 6,
                  child: Visibility(
                    visible: ("-1" == widget?.scid) && StringUtils.isEmpty(_styles) && (itemBean?.isMultiImage()??false),
                    child: Image.asset(
                      "images/icon_multi_images.png",
                      width: 45,
                      height: 18,
                    ),
                  ),
                ),
              ],
            ),
          ),
          Container(
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.only(bottomLeft: Radius.circular(4), bottomRight: Radius.circular(4))
            ),
            alignment: Alignment.centerLeft,
            padding: EdgeInsets.only(left: 8, top: 6, right: 8, bottom: 8),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  title,
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w600,
                    color: titleColor,
                  ),
                ),
                SizedBox(height: 2,),
                Text(
                  itemBean?.getTimeStr(),
                  style: TextStyle(
                      fontSize: 10,
                      color: Color(0XFF8B93A5)
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  String getLabel(String style){
    String label = "";
    if(StringUtils.isNotEmpty(widget?.column) && "其他" != widget?.column){
      label += widget?.column;
      label += "/";
    }
    if(StringUtils.isNotEmpty(style)){
      label += ConstantRepository.of().getStyleNameByStyle(style);
    }
    if(label.endsWith("/")){
      label = label.substring(0, label.length-1);
    }
    return label;
  }

  @override
  bool get wantKeepAlive => true;
}
